package com.study.ui.home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lbj.core.tool.data.SimpleTitle
import com.study.databinding.AdapterMainListBinding

class MainListAdapter :
    ListAdapter<SimpleTitle, MainListAdapter.ViewHolder>(MainListCallback()) {

    inner class ViewHolder(private val binding: AdapterMainListBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(position: Int) {
            binding.result = getItem(position)
            binding.index = position
            binding.presenter = Presenter()
            binding.executePendingBindings()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            AdapterMainListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(position)
    }

    inner class Presenter {
        fun onItemClick(v: View, result: SimpleTitle, index: Int) {
            result.title = "时间戳：${System.currentTimeMillis()}"
            notifyItemChanged(index)
        }
    }
}

class MainListCallback : DiffUtil.ItemCallback<SimpleTitle>() {
    override fun areItemsTheSame(oldItem: SimpleTitle, newItem: SimpleTitle): Boolean {
        return oldItem.id == newItem.id
    }

    override fun areContentsTheSame(oldItem: SimpleTitle, newItem: SimpleTitle): Boolean {
        return oldItem.title == newItem.title && oldItem.select == newItem.select
    }
}